import pandas as pd
import xgboost as xgb
import numpy as np
import warnings

warnings.filterwarnings('ignore')
from sklearn.model_selection import train_test_split

data = pd.read_csv('dataset.csv')
print(data)

X = data.iloc[:, :27]
Y = data.iloc[:, 27]
# print(X)
# print(Y)

X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.25, random_state=100)

xgb_train = xgb.DMatrix(X_train, label=y_train)
xgb_test = xgb.DMatrix(X_test, label=y_test)

# 设置模型参数

params = {
    'objective': 'multi:softmax',
    'eta': 0.1,
    'max_depth': 5,
    'num_class': 3
}

watchlist = [(xgb_train, 'train'), (xgb_test, 'test')]
# 设置训练轮次，这里设置60轮
num_round = 60
bst = xgb.train(params, xgb_train, num_round, watchlist)

# 模型预测

pred = bst.predict(xgb_test)
print(pred)

# 模型评估

# error_rate=np.sum(pred!=test.lable)/test.lable.shape[0]
error_rate = np.sum(pred != y_test) / y_test.shape[0]

print('测试集错误率(softmax):{}'.format(error_rate))

accuray = 1 - error_rate
print('测试集准确率：%.4f' % accuray)

# 模型保存
bst.save_model("xgboost.model")

# 模型加载
bst = xgb.Booster()
bst.load_model("xgboost.model")
pred = bst.predict(xgb_test)
print(pred)
